package wh.coach._collection;

import java.util.Map;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author hangwen
 * @date 2023/6/25
 */
public class _TreeMap {
    public static void main(String[] args) {
        //TreeMap的单值检索性能不及hashMap，但是因为实现了NavigableMap,可以支持范围查询

        //约束
        //1.KEY必须实现Comparable接口
        //2.equals和compare方法必须逻辑等价：即equals返回true,compare必须返回0

        TreeMap<Integer, String> treeMap = new TreeMap<>();

        treeMap.put(5, "E");
        treeMap.put(1, "A");
        treeMap.put(2, "B");
        treeMap.put(4, "C");
        treeMap.put(5, "D");

        System.out.println(treeMap);

        //最小的kv对
        Map.Entry<Integer, String> first = treeMap.firstEntry();
        System.out.println(first);
        //最大的kv对
        Map.Entry<Integer, String> last = treeMap.lastEntry();
        System.out.println(last);

        //>3的map
        final SortedMap<Integer, String> _gt_3 = treeMap.tailMap(3);
        System.out.println(_gt_3);

        //>=3的map
        final NavigableMap<Integer, String> _gte_3 = treeMap.tailMap(3, true);
        System.out.println(_gte_3);

        //<3的map
        final SortedMap<Integer, String> _lt_3 = treeMap.headMap(3);
        System.out.println(_lt_3);

        //<=3的map
        final NavigableMap<Integer, String> _lte_3 = treeMap.headMap(3, true);
        System.out.println(_lte_3);

        //<=3的最大值
        final Map.Entry<Integer, String> floor_3 = treeMap.floorEntry(3);
        System.out.println(floor_3);

        //<3的最大值
        final Map.Entry<Integer, String> lower_3 = treeMap.lowerEntry(3);
        System.out.println(lower_3);

        //>=3的最小值
        final Map.Entry<Integer, String> ceiling_3 = treeMap.ceilingEntry(3);
        System.out.println(ceiling_3);

        //>3的最小值
        final Map.Entry<Integer, String> higher_3 = treeMap.higherEntry(3);
        System.out.println(higher_3);

        //>=2 <4的值
        final NavigableMap<Integer, String> subMap = treeMap.subMap(2, true, 4, false);
        System.out.println(subMap);

        //最佳实践:有自然排序需求 或者 有范围查询需求 用TreeMap
    }
}
